#include "udpworker.h"

#include <QDebug>
#include <QThread>

#include <QNetworkInterface>

UdpWorker::UdpWorker(const char *inface, QObject *parent) : QObject(parent)
{
    if (!mUdpRxSocket.bind(QHostAddress("255.255.255.255"), 28123, QUdpSocket::DefaultForPlatform))
    {
        qDebug() << "bind error";
    }
    mUdpRxSocket.setMulticastInterface(QNetworkInterface::interfaceFromName(inface));
    connect(&mUdpRxSocket, SIGNAL(readyRead()), this, SLOT(dataRecv()));

    if (!mUdpTxSocket.bind(QHostAddress("255.255.255.255"), 28124, QUdpSocket::DefaultForPlatform))
    {
        qDebug() << "bind error";
    }
    mUdpTxSocket.setMulticastInterface(QNetworkInterface::interfaceFromName(inface));
}

UdpWorker::~UdpWorker()
{
    mUdpRxSocket.close();
    mUdpTxSocket.close();
}

int UdpWorker::dataSend(const QByteArray &datagram)
{
//    qDebug() << "udp data send";
    int bytes = mUdpTxSocket.writeDatagram(datagram, datagram.size(), QHostAddress("224.1.1.1"), 8640);

    return bytes;
}

int UdpWorker::dataSend(const char *datagram, int n)
{
//    qDebug() << "udp data send";
    int bytes = mUdpTxSocket.writeDatagram(datagram, n, QHostAddress("224.1.1.1"), 8640);

    return bytes;
}

bool UdpWorker::waitForRecvBytes(int msec)
{
    return mUdpRxSocket.waitForReadyRead(msec);
}

void UdpWorker::dataRecv()
{
    if (mUdpRxSocket.hasPendingDatagrams())
    {
        qDebug() << "read udp data";
        mRxDatagram.resize(mUdpRxSocket.pendingDatagramSize());
        mUdpRxSocket.readDatagram(mRxDatagram.data(), mRxDatagram.size());

        emit dataRecvdBytes(mRxDatagram);
    }
}
